package com.goldgov.notice.web;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.gtiles.components.securityworkbench.bean.SwbAuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.goldgov.addressbook.service.AddressBookGroupQuery;
import com.goldgov.kcloud.core.json.JsonObject;
import com.goldgov.kcloud.core.json.JsonQueryObject;
import com.goldgov.kcloud.core.json.JsonSuccessObject;
import com.goldgov.login.web.model.LoginAuthUser;
import com.goldgov.notice.service.Notice;
import com.goldgov.notice.service.NoticeQuery;
import com.goldgov.notice.service.NoticeService;
import com.goldgov.notice.service.NoticeUser;
import com.goldgov.notice.service.NoticeUserQuery;
import com.goldgov.notice.service.NoticeUserService;
import com.goldgov.utils.DataUtil;
import com.goldgov.utils.JiguangPush;
import com.goldgov.utils.JsonUtil;
import com.goldgov.utils.PropertyUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

/** 
 * @ClassName: NoticeController 
 * @Description: TODO
 * @author MaN
 * @date 2018年7月16日 
 */

@RestController
@RequestMapping("/workbench/notice")
@Api("通知公告接口")
public class NoticeController {

	@Autowired
	private NoticeService noticeService;
	
	@Autowired
	private NoticeUserService noticeUserService;
	
	@PostMapping
	@ApiOperation(value = "新增通知公告", notes ="")
	public JsonObject<Object> addNotice(Notice obj,Model model,HttpServletRequest request){
		String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		SwbAuthUser u=LoginAuthUser.getUserByAdmin(request);
		obj.setUserID(u.getEntityID());//发布人id
		obj.setUserName(u.getName());
		obj.setLastModifyTime(date);
		obj.setCreateDate(new Date());
		obj.setActiveState(AddressBookGroupQuery.ACTIVESTATE_YES);
//		if (PropertyUtil.objectNotEmpty(obj.getNoticeType()) && obj.getNoticeType().equals("3")) {
//			obj.setReceiptState(NoticeQuery.IS_RECEIPT_NO);
//		}
		if (!PropertyUtil.objectNotEmpty(obj.getSourceType())) {
			obj.setSourceType(NoticeQuery.ZDY_NOTICE);
		}
		if (obj.getPublishState() == null) {
			obj.setPublishState(AddressBookGroupQuery.PUBLISH_NO);
		}else if(obj.getPublishState().intValue() == 2) {
			obj.setPulishDate(new Date());
		}
		if (noticeService.addNotice(obj)) {
			sendNotice(obj);
			return JsonUtil.success(obj,"保存成功!");
		}else {
			return JsonUtil.error("系统出错,请联系管理员!");
		}
	}
	
	@GetMapping("/listNotice")
	@ApiOperation(value = "通知公告", notes ="")
	@ApiImplicitParams({@ApiImplicitParam(name = "searchType", value = "列表类型", paramType = "query"),
		@ApiImplicitParam(name = "searchPulishBeginDate", value = "发布时间", paramType = "query"),
		@ApiImplicitParam(name = "searchPulishEndDate", value = "发布时间", paramType = "query"),
		@ApiImplicitParam(name = "searchNoticeType", value = "消息类型", paramType = "query")})
	public JsonQueryObject<Notice> listNotice(@ApiIgnore NoticeQuery query,HttpServletRequest request){
		SwbAuthUser u=LoginAuthUser.getUserByAdmin(request);
		Integer type=query.getSearchType();
		//收件箱
		List<Notice> list;
		if(null!=type && type==2) {
			query.setSearchReceiveUserID(u.getEntityID());
			list=noticeService.getNoticeReceivedList(query);
		}else {//发件箱
			query.setSearchUserID(u.getEntityID());
			list=noticeService.getNoticeList(query);
		}
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	@GetMapping("/listNoticeFull")
	@ApiOperation(value = "通知公告", notes ="")
	@ApiImplicitParams({@ApiImplicitParam(name = "searchType", value = "列表类型", paramType = "query"),
		@ApiImplicitParam(name = "searchPulishBeginDate", value = "发布时间", paramType = "query"),
		@ApiImplicitParam(name = "searchPulishEndDate", value = "发布时间", paramType = "query"),
		@ApiImplicitParam(name = "searchNoticeType", value = "消息类型", paramType = "query")})
	public JsonQueryObject<Notice> listNoticeFull(@ApiIgnore NoticeQuery query,HttpServletRequest request){
		//SwbAuthUser u=LoginAuthUser.getUserByAdminTest(request);
		//收件箱
		List<Notice> list;
		if (PropertyUtil.objectNotEmpty(query.getSearchType())) {
			if (query.getSearchType()==2) {
				SwbAuthUser u=LoginAuthUser.getUserByAdmin(request);
				query.setSearchReceiveUserID(u.getEntityID());
				if (PropertyUtil.objectNotEmpty(query.getSearchNoticeType())) {
					if (query.getSearchNoticeType().equals("-1")) {
						query.setSearchNoticeType(null);
					}
				}
			}
			list = noticeService.getNoticeListFullReceive(query);
		}else {
			
			list=noticeService.getNoticeListFull(query);
		}
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	@GetMapping("/listNoticeReceiveUser")
	@ApiOperation(value = "通知公告", notes ="")
	@ApiImplicitParams({@ApiImplicitParam(name = "searchNoticeID", value = "通知主键", paramType = "query"),
			@ApiImplicitParam(name = "searchUserName", value = "人名", paramType = "query")})
	public JsonQueryObject<NoticeUser> listNoticeReceiveUser(@ApiIgnore NoticeUserQuery query,HttpServletRequest request){
		//SwbAuthUser u=LoginAuthUser.getUserByAdminTest(request);
		//收件箱
		List<NoticeUser> noticeUserList = noticeUserService.getNoticeUserList(query);
		query.setResultList(noticeUserList);
		return new JsonQueryObject<>(query);
	}
	
	@PostMapping("/updateNotice")
	@ApiOperation(value = "修改通知公告", notes ="")
	public JsonObject<Object> updateNotice(Notice obj,HttpServletRequest request){
		obj.setLastModifyTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		if(PropertyUtil.objectNotEmpty(obj.getNoticeID())) {
			if (noticeService.updateNotice(obj)) {
				sendNotice(obj);
			}	
			return JsonUtil.success("修改成功!");
		}else {
			return JsonUtil.error("系统出错,缺少通知ID!");
		}
	}
	@DeleteMapping
	@ApiOperation(value = "删除通知公告", notes = "")
	public JsonObject<Object> deleteAddressBookGroup(@ApiParam(value = "noticeID", required = true) @RequestParam("ids") String[] ids,HttpServletRequest request,HttpServletResponse response) throws Exception {
		if (noticeService.deleteNotice(ids)) {
			return JsonUtil.success("删除成功!");
		}else {
			return JsonUtil.error("系统出错,请联系管理员!");
		}
	}
	@GetMapping("/sendNotice")
	@ApiOperation(value = "发送通知公告", notes ="")
	public JsonObject<Object> sendNotice(Notice obj,HttpServletRequest request){
		String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		obj.setLastModifyTime(date);
		obj.setPublishState(AddressBookGroupQuery.PUBLISH_YES);
		obj.setPulishDate(new Date());
		noticeService.updateNotice(obj);
		NoticeUserQuery query=new NoticeUserQuery();
		query.setSearchNoticeID(obj.getNoticeID());
		query.setPageSize(-1);
		List<NoticeUser> userList=noticeUserService.getNoticeUserList(query);
		Notice notice = noticeService.getNotice(obj.getNoticeID());
		for(NoticeUser user:userList) {
				Map<String, String> params = new HashMap<>();
				params.put("userID", user.getUserID().replace("-", "")); //接收人
				params.put("modelName", notice.getNoticeName()); //标题
				params.put("content", notice.getNoticeType() == null ? "【通知】" + notice.getNoticeContent() : notice.getNoticeContent()); //内容
				
				Map<String, String> map = new HashMap<>();  //传递的参数
				map.put("noticeId", notice.getNoticeID());
				map.put("id", "");
				map.put("noticeType", DataUtil.SYSTEM_NOTICE);
				map.put("sourceType", notice.getSourceType() == null ? "2" : notice.getSourceType().toString());
				params.put("mapString", JSONObject.toJSONString(map));
				try {
					JiguangPush.jsoup(params);
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return JsonSuccessObject.SUCCESS;
	}
	@GetMapping("/sendNoticeAgain")
	@ApiOperation(value = "点击再次发送", notes ="")
	public JsonSuccessObject<Notice> sendNoticeAgain(@ApiParam(value = "noticeID", required = true) @RequestParam("noticeID") String noticeID,HttpServletRequest request){
		NoticeUserQuery query=new NoticeUserQuery();
		query.setSearchNoticeID(noticeID);
		List<NoticeUser> userList=noticeUserService.getNoticeUserList(query);
		String[] userIDs=null;
		String[] userNames=null;
		if(null!=userList && userList.size()>0) {
			int i=0;
			int j=0;
			userIDs=new String[userList.size()];
			userNames=new String[userList.size()];
			for(NoticeUser user:userList) {
				userIDs[i++]=user.getUserID();
				userNames[j++]=user.getUserName();
			}
		}
		Notice notice=new Notice();
		notice.setUserIDs(userIDs);
		notice.setUserNames(userNames);
		JsonSuccessObject<Notice> returnResult = new JsonSuccessObject<Notice>(notice);
		return returnResult;
	}
	@PostMapping("/updateNoticeUser")
	@ApiOperation(value = "添加回执", notes ="")
	public JsonObject<Object>updateNoticeUser(NoticeUser obj,HttpServletRequest request){
		String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		SwbAuthUser u=LoginAuthUser.getUserByAdmin(request);
		obj.setUserID(u.getEntityID());
		obj.setIsRead(NoticeUserQuery.IS_READ_YES);
		obj.setReceiptDate(date);
		noticeUserService.updateNoticeUser(obj);
		return JsonSuccessObject.SUCCESS;
	}
	
	
	@GetMapping("/{id}")
	@ApiOperation(value = "根据主键查询会议记录", notes ="工作日志详情")
	public JsonSuccessObject<Notice> getConference(@ApiParam(value="noticeID",required=false) @PathVariable("id") String id,HttpServletRequest request){
		Notice notice = noticeService.getNotice(id);
		JsonSuccessObject<Notice> returnResult = new JsonSuccessObject<>(notice);
		return returnResult;
	}
	//添加关联关系
	public void sendNotice(Notice notice) {
		//添加关联关系记录
		String[] userIDs=notice.getUserIDs();
		if(null!=userIDs && userIDs.length>0) {
			NoticeUserQuery query=new NoticeUserQuery();
			query.setSearchNoticeID(notice.getNoticeID());
			query.setPageSize(-1);
			List<NoticeUser> userList=noticeUserService.getNoticeUserList(query);
			if(null!=userList && userList.size()>0) {
				//删除关联关系
				noticeUserService.deleteNoticeUser(notice.getNoticeID());
			}
			for(String userID:userIDs) {
				NoticeUser user=new NoticeUser();
				user.setNoticeID(notice.getNoticeID());
				user.setUserID(userID);
				user.setIsRead(NoticeUserQuery.IS_READ_NO);
				user.setNoticeContentMobile(notice.getNoticeContent());
				noticeUserService.addNoticeUser(user);
			}
		}
		
	}

	
}
